<template>
  <div class="avatar-upload">
    <!-- 头像显示区域 -->
    <div class="avatar-display">
      <el-avatar 
        :size="120" 
        :src="displayAvatar" 
        :icon="UserFilled"
        class="avatar-image"
        @error="handleImageError"
      />
    </div>
    
    <!-- 上传按钮 -->
    <div class="upload-actions">
      <el-upload
        ref="uploadRef"
        :show-file-list="false"
        :before-upload="beforeUpload"
        :on-success="handleSuccess"
        :on-error="handleError"
        :disabled="loading"
        accept="image/*"
        action="http://localhost:8080/upload"
      >
        <el-button 
          type="primary" 
          size="small"
          :loading="loading"
          :icon="Upload"
        >
          {{ loading ? '上传中...' : '更换头像' }}
        </el-button>
      </el-upload>
      
      <div class="upload-tips">
        <p>支持 JPG、PNG 格式</p>
        <p>文件大小不超过 2MB</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import { UserFilled, Upload } from '@element-plus/icons-vue'

// 定义props和emits
const props = defineProps({
  currentAvatar: {
    type: String,
    default: ''
  },
  loading: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['upload-success'])

// 上传组件引用
const uploadRef = ref()

// 图片加载失败状态
const imageLoadError = ref(false)

// 计算属性：显示的头像
const displayAvatar = computed(() => {
  // 如果图片加载失败，返回空字符串显示默认图标
  if (imageLoadError.value) {
    return ''
  }
  
  // 如果有头像URL，确保它是完整的URL
  if (props.currentAvatar) {
    // 如果是相对路径，需要添加基础URL
    if (props.currentAvatar.startsWith('/')) {
      return props.currentAvatar
    }
    // 如果是完整URL，直接使用
    if (props.currentAvatar.startsWith('http')) {
      return props.currentAvatar
    }
    // 其他情况，假设是相对路径
    return props.currentAvatar
  }
  return ''
})

// 处理图片加载错误
const handleImageError = () => {
  console.warn('头像图片加载失败:', props.currentAvatar)
  imageLoadError.value = true
}

// 监听头像URL变化，重置错误状态
watch(() => props.currentAvatar, () => {
  imageLoadError.value = false
})

// 上传前验证
const beforeUpload = (file) => {
  // 检查文件类型
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
    return false
  }
  
  // 检查文件大小 (2MB)
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  
  return true
}

// 上传成功回调
const handleSuccess = (response, file) => {
  if (response && response.data) {
    // 触发上传成功事件，传递服务器返回的图片URL
    emit('upload-success', response.data)
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error('头像上传失败')
  }
}

// 上传失败回调
const handleError = (error) => {
  console.error('头像上传失败:', error)
  ElMessage.error('头像上传失败')
}
</script>

<style scoped>
.avatar-upload {
  text-align: center;
  padding: 20px 0;
}

.avatar-display {
  margin-bottom: 20px;
}

.avatar-image {
  border: 3px solid #e4e7ed;
  transition: all 0.3s ease;
}

.avatar-image:hover {
  border-color: #409eff;
  transform: scale(1.05);
}

.upload-actions {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.upload-tips {
  color: #909399;
  font-size: 12px;
  line-height: 1.4;
  text-align: center;
}

.upload-tips p {
  margin: 2px 0;
}

:deep(.el-upload) {
  display: block;
}

:deep(.el-button) {
  border-radius: 20px;
  padding: 8px 20px;
  font-weight: 500;
}

:deep(.el-button.is-loading) {
  pointer-events: none;
}

/* 头像加载失败时的样式 */
:deep(.el-avatar) {
  background-color: #f5f7fa;
  color: #c0c4cc;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .avatar-image {
    width: 100px !important;
    height: 100px !important;
  }
  
  .upload-tips {
    font-size: 11px;
  }
}
</style>